package com.hongxun.budget.ui.dialog;

import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Spinner;
import android.widget.TextView;

import com.hongxun.budget.R;
import com.hongxun.budget.greendao.BEntryCriteriaEntityDao;
import com.hongxun.budget.greendao.DaoSession;
import com.hongxun.budget.ui.adapter.SpinnerAdapter;
import com.hongxun.budget.utils.DBUtils;
import com.hongxun.budget.utils.GreenDaoManager;
import com.hongxun.budget.utils.RecyclerViewUtils;
import com.hongxun.budget.utils.T;
import com.hongxun.greenentity.tk.BDataDictionaryEntity;
import com.hongxun.greenentity.tk.BEntryCriteriaEntity;
import com.hongxun.greenentity.tk.BEstimateEntity;
import com.hongxun.greenentity.tk.BProjectApplicationEntity;
import com.hongxun.interfaces.ResponseListener;
import com.jessewu.library.SuperAdapter;
import com.jessewu.library.view.ViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 准入条件选择
 */

public class EntryCriteriaDialog extends BaseCenterFragmentDialog {

    @BindView(R.id.spinner)
    Spinner spinner;
    @BindView(R.id.list)
    RecyclerView recyclerView;

    String dKey;//dKey:项目类型
    ResponseListener listener;
    List<BEntryCriteriaEntity> datas = new ArrayList<>();//源数据
    SuperAdapter<BEntryCriteriaEntity> superAdapter;
    private Map<Integer, Boolean> checkMap = new HashMap<>();//记录被勾选项，防止错乱

    BProjectApplicationEntity applicationEntity;//项目申请书
    List<BEstimateEntity> bEstimateEntity;//项目简表
    List<BEntryCriteriaEntity> entities;//已经选择了的准入条件
    List<String> noIn;//已选择的对应的准入项ID
    List<String> entitiesList;//项目简表对应的准入项ID
    DaoSession session;

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_entrycriteria;
    }

    @Override
    protected void initViews() {
        session = GreenDaoManager.getInstance().getmDaoSession();
        bEstimateEntity = DBUtils.getBEstimateEntities(dKey);//获取项目简表
        entitiesList = new ArrayList<>();
        noIn = new ArrayList<>();
        for (BEstimateEntity b : bEstimateEntity) {
            entitiesList.add(b.getBGuid());
        }
        for (BEntryCriteriaEntity b : entities) {
            noIn.add(b.getGuid());
        }
        //获取对应所有的准入条件
        List<BEntryCriteriaEntity> list = session.getBEntryCriteriaEntityDao().queryBuilder()
                .where(BEntryCriteriaEntityDao.Properties.ECType.eq(dKey), BEntryCriteriaEntityDao.Properties.Guid.notIn(noIn)
                        , BEntryCriteriaEntityDao.Properties.BGuid.in(entitiesList)).
                        orderAsc(BEntryCriteriaEntityDao.Properties.ECSaml, BEntryCriteriaEntityDao.Properties.ECNum).list();
        final List<String> spinnerList = new ArrayList<>();
        final Map<String, String> map = new HashMap<>();//记录key与value
        for (BEntryCriteriaEntity e : list) {//获取子类对应的名称
            BDataDictionaryEntity unique = DBUtils.getBDataDictionaryEntity("progect_type_smal_" + e.getECType(), e.getECSaml());
            if (unique != null && !spinnerList.contains(unique.getDValue())) {
                spinnerList.add(unique.getDValue());
                map.put(unique.getDValue(), e.getECSaml());
            }
        }
        spinner.setAdapter(new SpinnerAdapter<String>(getActivity(), spinnerList, spinner));
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                checkMap.clear();
                String ectype = map.get(spinnerList.get(position));//获取到对应的KEY
                getData(ectype);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        recyclerView.setLayoutManager(RecyclerViewUtils.getLinearLayoutManagerForVertical(getActivity()));
        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        recyclerView.setAdapter(superAdapter = new SuperAdapter<BEntryCriteriaEntity>(R.layout.content_dialog_checklist) {
            @Override
            public void bindView(ViewHolder viewHolder, final BEntryCriteriaEntity t, final int i) {
                TextView textView = viewHolder.getView(R.id.content);
                textView.setText(t.getECCriteria());
                CheckBox checkBox = viewHolder.getView(R.id.checkBox);
                checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                        if (b == true) checkMap.put(i, true);
                        else checkMap.remove(i);

                    }
                });
                if (checkMap != null && checkMap.containsKey(i)) {
                    checkBox.setChecked(true);
                } else {
                    checkBox.setChecked(false);
                }
            }
        });
        superAdapter.setData(datas);
        if (spinnerList.size() > 0)
            getData(map.get(spinnerList.get(0)));
        else T.showLong(context, "为获取相关数据");
    }

    void getData(String ectype) {
        List<BEntryCriteriaEntity> list = session.getBEntryCriteriaEntityDao().queryBuilder()
                .where(BEntryCriteriaEntityDao.Properties.ECType.eq(dKey), BEntryCriteriaEntityDao.Properties.Guid.notIn(noIn)
                        , BEntryCriteriaEntityDao.Properties.BGuid.in(entitiesList), BEntryCriteriaEntityDao.Properties.ECSaml.eq(ectype)).
                        orderAsc(BEntryCriteriaEntityDao.Properties.ECSaml, BEntryCriteriaEntityDao.Properties.ECNum).list();
        datas.clear();
        datas.addAll(list);
        superAdapter.notifyDataSetChanged();
    }

    public EntryCriteriaDialog setDKey(String dKey) {
        this.dKey = dKey;
        return this;
    }

    public EntryCriteriaDialog setEntities(List<BEntryCriteriaEntity> entities) {
        this.entities = entities;
        return this;
    }

    public EntryCriteriaDialog setListener(ResponseListener listener) {
        this.listener = listener;
        return this;
    }

    @OnClick(R.id.cancel)
    public void onViewClicked() {
        List<BEntryCriteriaEntity> resultDatas = new ArrayList<>();//选择的结果
        for (Integer integer : checkMap.keySet()) {
            resultDatas.add(datas.get(integer));
        }
        listener.response(resultDatas, checkMap);
        dismiss();
    }
}
